import {mapGetters, mapMutations, mapActions} from 'vuex'
import {playMode} from './config'
import {shuffle} from './utils'

// mini播放器显示时，滚动组件scroll的refresh逻辑覆盖
export const playlistMixin = {
  computed: {
    ...mapGetters(['playlist'])
  },
  mounted () {
    this.handlePlaylist(this.playlist)
  },
  activated () {
    this.handlePlaylist(this.playlist)
  },
  watch: {
    playlist (newVal) {
      this.handlePlaylist(this.playlist)
    }
  },
  method: {
    handlePlaylist () {
      throw new Error('Component must implement handlePlaylist method')
    }
  }
}

// player和playlist组件复用逻辑
export const playerMixin = {
  computed: {
    ...mapGetters([
      'playlist',
      'currentSong',
      'mode',
      'sequenceList',
      'favoriteList'
    ]),
    iconMode () {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    }
  },
  methods: {
    ...mapMutations({
      setCurrentIndex: 'SET_CURRENT_INDEX',
      setPlayMode: 'SET_PLAY_MODE',
      setPlaylist: 'SET_PLAYLIST'
    }),
    ...mapActions(['saveFavorite', 'deleteFavorite']),
    changeMode () {
      const mode = (this.mode + 1) % 3
      this.setPlayMode(mode)
      let list = null
      if (mode === playMode.random) {
        list = shuffle(this.sequenceList)
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlaylist(list)
    },
    resetCurrentIndex (list) {
      let index = list.findIndex((item) => {
        return item.id === this.currentSong.id
      })
      this.setCurrentIndex(index)
    },
    // 收藏歌曲相关
    isFavorite (song) {
      const index = this.favoriteList.findIndex(item => item.id === song.id)
      return index > -1
    },

    getFavoriteIcon (song) {
      return this.isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
    },

    toggleFavorite (song) {
      this.isFavorite(song) ? this.deleteFavorite(song) : this.saveFavorite(song)
    }
  }
}

// search 和 add-song组件复用逻辑
export const searchMixin = {
  data () {
    return {
      query: ''
    }
  },
  computed: {
    ...mapGetters(['searchHistory'])
  },
  methods: {
    ...mapActions([
      'saveSearchHistory',
      'deleteSearchHistory'
    ]),
    onQueryChange (query) {
      this.query = query
    },
    saveSearch () {
      this.saveSearchHistory(this.query)
    },
    setQuery (query) {
      this.$refs.searchBox.setQuery(query)
    },
    scrollStarted () {
      this.$refs.searchBox.blurInput()
    }
  }
}
